package com.ganlinux.pangoo.tools;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {
	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	private static final OkHttpClient mOkHttpClient = new OkHttpClient();
	static{
		mOkHttpClient.newBuilder().connectTimeout(30, TimeUnit.SECONDS);
	}
	/**
	 * 该不会开启异步线程。
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static Response execute(Request request) throws IOException{
		return mOkHttpClient.newCall(request).execute();
	}
	/**
	 * 开启异步线程访问网络
	 * @param request
	 * @param responseCallback
	 */
	public static void enqueue(Request request, Callback responseCallback){
		mOkHttpClient.newCall(request).enqueue(responseCallback);
	}
	/**
	 * 开启异步线程访问网络, 且不在意返回结果（实现空callback）
	 * @param request
	 */
	public static void enqueue(Request request){
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			public void onFailure(Call call, IOException e) {

			}

			public void onResponse(Call call, Response response) throws IOException {

			}

		});
	}
	public static String getStringFromServer(String url) throws IOException{
		Request request = new Request.Builder().url(url).build();
		Response response = execute(request);
		if (response.isSuccessful()) {
			String responseUrl = response.body().string();
			return responseUrl;
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}
	private static final String CHARSET_NAME = "UTF-8";
	/**
     * 这里使用了HttpClinet的API。只是为了方便
     * @param params
     * @return
     */
    /*public static String formatParams(List<BasicNameValuePair> params){
        return URLEncodedUtils.format(params, CHARSET_NAME);
    }
    *//**
     * 为HttpGet 的 url 方便的添加多个name value 参数。
     * @param url
     * @param params
     * @return
     *//*
    public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){
        return url + "?" + formatParams(params);
    }
 
	*//**
	 * 为HttpGet 的 url 方便的添加1个name value 参数。
	 * @param url
	 * @param name
	 * @param value
	 * @return
	 *//*
	public static String attachHttpGetParam(String url, String name, String value){
		return url + "?" + name + "=" + value;
	}


	public static String postJsonBody(String url, String json) throws IOException {
		RequestBody body = RequestBody.create(JSON, json);
		Request request = new Request.Builder()
				.url(url)
				.post(body)
				//	      .method("post", body)
				.build();
		Response response = mOkHttpClient.newCall(request).execute();
		if (response.isSuccessful()) {

			return response.body().string();
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}
	public static String postFormbody(String url, Object object) throws IOException {
		FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
		try {
			Field[] fields = object.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				String name = field.getName();
				Object value = JsonUtil.getFieldValueByName(name, object);
				if (value == null) {
					value = "";
				}
				formEncodingBuilder.add(name, value.toString());
			}


		} catch (Exception e) {
			e.printStackTrace();
		}
		RequestBody formBody = formEncodingBuilder.build();


		*//*.add("query", "银行")
	    .add("region", "北京")
	    .add("output", "json")
	    .add("ak", "jSOARuabErrgYw0gzsqiBwIf716FPFtY")
	    .add("mcode", "6D:00:00:5B:5A:92:E1:BA:1F:B4:F4:8E:8C:DD:72:CE:EC:6C:EE:EA;www.ganlinux.com.android")
	    .build();*//*

		Request request = new Request.Builder()
				.url(url)
				.post(formBody)
				.build();

		Response response = mOkHttpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			return response.body().string();
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}*/
}
